using UnityEngine;
using UnityEditor;

public class RenderToCubeMap : EditorWindow
{
    private GameObject obj;
    private Cubemap cubeMap;

    [MenuItem("Tools/Render to CubeMap")]
    static void OpenWindow()
    {
        RenderToCubeMap window = GetWindow<RenderToCubeMap>("Render to CubeMap");
        window.Show();
    }

    private void OnGUI()
    {
        GUILayout.Label("选择物体");
        obj = EditorGUILayout.ObjectField(obj, typeof(GameObject), true) as GameObject;
        GUILayout.Label("选择需要写入的CubeMap");
        cubeMap = EditorGUILayout.ObjectField(cubeMap, typeof(Cubemap), false) as Cubemap;

        if (GUILayout.Button("开始生成"))
        {
            if (obj == null || cubeMap == null)
            {
                EditorUtility.DisplayDialog("错误", "对象选择为空", "确认");
                return;
            }

            // 创建临时相机对象
            GameObject tmpObj = new GameObject("CubemapCamera");
            tmpObj.transform.position = obj.transform.position;
            Camera camera = tmpObj.AddComponent<Camera>();

            // 渲染到Cubemap
            camera.RenderToCubemap(cubeMap);

            // 销毁临时相机对象
#if UNITY_EDITOR
            DestroyImmediate(tmpObj);
#else
            Destroy(tmpObj);
#endif
        }
    }
}